package com.wander.nio.chat;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyServer {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ArrayList<Socket> clients = new ArrayList<>();
        try {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.bind(new InetSocketAddress(8888));
            while (true) {
                //接受客户端
                Socket client = serverSocket.accept();
                System.out.println("客户端已连接：" + client.getRemoteSocketAddress());
                clients.add(client);
                executorService.execute(new ClientTask(client, clients));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static class ClientTask implements Runnable {
        private Socket socket;
        private ArrayList<Socket> clients;

        public ClientTask(Socket socket, ArrayList<Socket> clients) {
            this.socket = socket;
            this.clients = clients;
        }

        @Override
        public void run() {
            //监听客户端发送消息
            while (true) {
                try {
                    InputStream inputStream = socket.getInputStream();
                    DataInputStream dis = new DataInputStream(inputStream);
                    String msg = dis.readUTF();
                    if ("exit".equals(msg)) {
                        socket.close();
                    } else {
                        System.out.println("收到客户端" + socket.getRemoteSocketAddress() + "发送消息： " + msg);
                        String message = socket.getRemoteSocketAddress() + "发送消息： " + msg;
                        //消息群发
                        for (Socket client : clients) {
                            try {
                                OutputStream os = client.getOutputStream();
                                DataOutputStream dos = new DataOutputStream(os);
                                dos.writeUTF(message);
                                dos.flush();
                            } catch (IOException e) {
                                clients.remove(client);
                                throw new RuntimeException(e);
                            }
                        }
                    }
                } catch (IOException e) {
                    System.out.println("客户端已断开：" + socket.getRemoteSocketAddress());
                    break;
                }
            }
        }
    }
}
